﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Autodesk.AutoCAD.Interop;
using Autodesk.AutoCAD.Interop.Common;
using System.IO;
using System.Collections;

namespace 根据浇注信息划分大坝模型
{
    public partial class Form1 : Form
    {
        Autodesk.AutoCAD.Interop.AcadApplication AcadApp;
        Autodesk.AutoCAD.Interop.AcadDocument AcadDoc;

        public Form1()
        {
            InitializeComponent();
        }

        private void 启动CAD()
        {
            try
            {
                AcadApp =
               (AcadApplication)System.Runtime.InteropServices.Marshal.GetActiveObject("AutoCAD.Application");
                AcadDoc = AcadApp.ActiveDocument;
            }
            catch
            {
                OpenFileDialog pOpenDG = new OpenFileDialog();
                pOpenDG.Filter = "CAD文件(*.dwg)|*.dwg|CAD图形文件(*.dxf)|*.dxf";
                pOpenDG.Title = "打开CAD文件";
                pOpenDG.ShowDialog();
                string filePath = pOpenDG.FileName;
                if (filePath == "")
                {
                    MessageBox.Show("选择CAD文件无效！", "文件无效！");
                    Application.Exit();
                }
                AcadApp = new AcadApplication();
                AcadDoc = AcadApp.Documents.Open(filePath, null, null);
            }
            AcadApp.Application.Visible = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            启动CAD();
        }

        private void 读取浇筑信息数据_文本_Click(object sender, EventArgs e)
        {
            OpenFileDialog pOpenTxtDg = new OpenFileDialog();
            pOpenTxtDg.Title = "打开读取浇筑信息数据文件（文本文件）";
            pOpenTxtDg.Filter = "文本文件(*.txt)|*.txt|Dat格式(*.dat)|*.dat";
            pOpenTxtDg.ShowDialog();
            string filePath;
            filePath = pOpenTxtDg.FileName;
            if (filePath == "")
            {
                MessageBox.Show("文件路径错误!");
                return;
            }
            System.IO.StreamReader sr = System.IO.File.OpenText(filePath);
            infoDataGridView.Columns.Clear();
            infoDataGridView.Columns.Add("startTime", "开始浇筑时间");
            infoDataGridView.Columns.Add("endTime", "结束浇筑时间");
            infoDataGridView.Columns.Add("damIndex", "浇筑坝段序号");
            infoDataGridView.Columns.Add("startH", "开始浇筑时高程");
            infoDataGridView.Columns.Add("endH", "结束浇筑时高程");
            string txtLineString = "", tempValue, tempString;
            int i = 0;
            while ((txtLineString = sr.ReadLine()) != null)
            {
                //分析文本文件中每一行的数据,提取信息
                infoDataGridView.Rows.Add(1);
                //获取开始浇筑时间
                tempValue = Microsoft.VisualBasic.Strings.Left(txtLineString,
               txtLineString.IndexOf(" "));
                infoDataGridView.Rows[i].Cells[0].Value = tempValue;
                //获取结束浇注时间
                tempString = Microsoft.VisualBasic.Strings.Mid(txtLineString,
               txtLineString.IndexOf(" ") + 2);
                tempValue = Microsoft.VisualBasic.Strings.Left(tempString, tempString.IndexOf(" ")); 
 infoDataGridView.Rows[i].Cells[1].Value = tempValue;
                //获取浇注坝段序号
                tempString = Microsoft.VisualBasic.Strings.Mid(tempString, tempString.IndexOf(" ")+2); 
               
                tempValue = Microsoft.VisualBasic.Strings.Left(tempString, tempString.IndexOf(" ")); 
               
                infoDataGridView.Rows[i].Cells[2].Value = tempValue;
                //获取开始浇筑时的高度
                tempString = Microsoft.VisualBasic.Strings.Mid(tempString, tempString.IndexOf(" ")
               + 2);
                tempValue = Microsoft.VisualBasic.Strings.Left(tempString, tempString.IndexOf(" ")); 
               
                infoDataGridView.Rows[i].Cells[3].Value = tempValue;
                //获取浇筑结束时的高度
                tempString = Microsoft.VisualBasic.Strings.Mid(tempString, tempString.IndexOf(" ")
               + 2);
                infoDataGridView.Rows[i].Cells[4].Value = tempString;
                i++;
            }
        }

        private void 读取浇筑信息数据_Excel_Click(object sender, EventArgs e)
        {
            OpenFileDialog pOpenExcelDg = new OpenFileDialog();
            pOpenExcelDg.Title = "打开读取浇筑信息数据文件（Excel文件）";
            pOpenExcelDg.Filter = "Excel文件(*.xls)|*.xls";
            pOpenExcelDg.ShowDialog();
            string filePath;
            filePath = pOpenExcelDg.FileName;
            if (filePath == "")
            {
                MessageBox.Show("文件路径错误！");
                return;
            }

            Excel.Application excelApp = new Excel.ApplicationClass();
            Excel.Workbook myWorkBook;
            object missingValue = System.Reflection.Missing.Value;
            myWorkBook = excelApp.Workbooks.Open(filePath, missingValue, missingValue, missingValue,
           missingValue, missingValue
            , Excel.XlSaveAsAccessMode.xlNoChange, missingValue, missingValue, missingValue,
           missingValue, missingValue, missingValue, missingValue, missingValue); ;
            Excel.Worksheet newSheet;
            newSheet = (Excel.Worksheet)myWorkBook.Sheets[1];// 
            (Microsoft.Office.Interop.Excel.Worksheet)myWorkBook.Sheets[1];
            string tempValue = (string)((Excel.Range)newSheet.Cells[1, 1]).Text;
            int i = 1, j = 0;
            infoDataGridView.Columns.Clear();
            infoDataGridView.Columns.Add("startTime", "开始浇筑时间");
            infoDataGridView.Columns.Add("endTime", "结束浇筑时间");
            infoDataGridView.Columns.Add("damIndex", "浇筑坝段序号");
            infoDataGridView.Columns.Add("startH", "开始浇筑时高程");
            infoDataGridView.Columns.Add("endH", "结束浇筑时高程");
            while (tempValue != "")
            {
                infoDataGridView.Rows.Add(1);
                for (j = 0; j < 5; j++)
                {
                    tempValue = (string)((Excel.Range)newSheet.Cells[i, j + 1]).Text; ;
                    infoDataGridView.Rows[i - 1].Cells[j].Value = tempValue;
                }
                i++;
            }
            infoDataGridView.Rows.RemoveAt(i - 2);
            excelApp.Quit();

        }

        private void 划分模型_Click(object sender, EventArgs e)
        {
            AcadDoc.Layers.Add("划分后模型");
            double startHeight, endHeight;
            string damIndexString, tempString;
            int damIndex;
            bool exitThisCircle = false;
            Int16[] FilterType = new Int16[2];
            object[] FilterData = new object[2];
            FilterType[0] = 8;
            FilterType[1] = 0;
            FilterData[1] = "3DSOLID";
            double[] point01 = new double[3];
            double[] point02 = new double[3];
            point01[0] = 0; point01[1] = 0; point01[2] = 0;
            point02[0] = 1000; point02[1] = 1000; point02[2] = 0;
            for (int i = 0; i < infoDataGridView.Rows.Count - 1; i++)
            {
                exitThisCircle = false;
                startHeight = Double.Parse(infoDataGridView.Rows[i].Cells[3].Value.ToString());
                endHeight = Double.Parse(infoDataGridView.Rows[i].Cells[4].Value.ToString());
                damIndexString = infoDataGridView.Rows[i].Cells[2].Value.ToString();
                while (!exitThisCircle)
                {
                    if (damIndexString.Contains(","))
                    {
                        tempString = Microsoft.VisualBasic.Strings.Left(damIndexString,
                       damIndexString.IndexOf(","));
                    }
                    else
                    {
                        tempString = damIndexString;
                        exitThisCircle = true;
                    }
                    damIndex = Int16.Parse(tempString);
                    AcadSelectionSet mySelectionSet;
                    mySelectionSet = AcadDoc.SelectionSets.Add("NewSelectionSet001");
                    FilterData[0] = "Dam" + damIndex.ToString();
                    mySelectionSet.Select(AcSelect.acSelectionSetAll, point01, point02, FilterType,
                   FilterData);
                    Acad3DSolid returnObj = (Acad3DSolid)mySelectionSet.Item(0);
                    BuildModel(returnObj, startHeight, endHeight);
                    AcadDoc.SelectionSets.Item("NewSelectionSet001").Delete();
                    damIndexString = Microsoft.VisualBasic.Strings.Mid(damIndexString,
                   damIndexString.IndexOf(",") + 2);
                }
            }
        }

        private void BuildModel(Acad3DSolid damObject, double startHeight, double endHeight)
        {
            Acad3DSolid damObjectCopy;
            Acad3DPolyline[] polyline = new Acad3DPolyline[1];
            AcadRegion regionObj;
            try
            {
                damObjectCopy = (Acad3DSolid)damObject.Copy();
                double[] regionCoords = new double[12], minPoint = new double[3], maxPoint = new
               double[3];
                object minPointObject, maxPointObject;
                damObjectCopy.GetBoundingBox(out minPointObject, out maxPointObject);
                minPoint = (double[])minPointObject;
                maxPoint = (double[])maxPointObject;
                regionCoords[0] = minPoint[0]; regionCoords[1] = minPoint[1]; regionCoords[2] =
               startHeight;
                regionCoords[3] = maxPoint[0]; regionCoords[4] = minPoint[1]; regionCoords[5] =
               startHeight;
                regionCoords[6] = maxPoint[0]; regionCoords[7] = maxPoint[1]; regionCoords[8] =
               startHeight;
                regionCoords[9] = minPoint[0]; regionCoords[10] = maxPoint[1]; regionCoords[11] =
               startHeight;

                polyline[0] = AcadDoc.ModelSpace.Add3DPoly(regionCoords);
                polyline[0].Closed = true;
                object[] tempObject;
                tempObject = (object[])AcadDoc.ModelSpace.AddRegion(polyline);
                regionObj = (AcadRegion)(tempObject[0]);
                Acad3DSolid boolObjectB;
                boolObjectB = AcadDoc.ModelSpace.AddExtrudedSolid(regionObj, endHeight - startHeight,
               0.0);
                damObjectCopy.Boolean(AcBooleanType.acIntersection, boolObjectB);
                damObjectCopy.Layer = "划分后模型";
                polyline[0].Delete();
                regionObj.Delete();
            }
            catch
            {
                polyline[0].Delete();
                erroInfoRichTextBox.Text += "在划分模型" + damObject.Layer.ToString()
                + "时：高程" + startHeight.ToString() + "至" + endHeight.ToString() + "出错！\n";
            }
        }
    }
}
